import { sgs_util } from "../../util"
import * as chatAction from 'chatAction'
import * as chatSystemAction from "chatSystemAction"

const chatInitialState: chatAction.ChatState = {
    messages: []
}

export function chatReducer(
    state = chatInitialState,
    action
) {

    const mes = sgs_util.isObjectExist<Record<keyof chatAction.messages, chatAction.ChatState>>({
        SEND_MESSAGE: {
            messages: [...state.messages, action.payload]
        },
        DELETE_MESSAGE: {
            messages: state.messages.filter(el => el.timestamp !== action.meta.timestamp)
        }
    }, action.type)

    return mes || state
}


const chatSystemInitialState: chatSystemAction.SystemState = {
    loggedIn: false,
    session: '',
    userName: ''
}

export function chatSystemReducer(state = chatSystemInitialState, action) {
    const mes = sgs_util.isObjectExist<Record<keyof chatSystemAction.messages, chatSystemAction.SystemState>>({
        UPDATE_SESSION: {
            ...state,
            ...action.payload
        }
    }, action.type)

    return mes || state
}